package com.baorant;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class RollCallApp extends JFrame {
    private List<String> studentList = new ArrayList<>();
    private List<String> calledStudents = new ArrayList<>();
    private JLabel fileLabel;
    private JLabel displayLabel;
    private JButton startButton;
    private JButton stopButton;
    private JButton loadButton;
    private DefaultListModel<String> listModel;
    private JList<String> calledList;
    private Timer timer;
    private Random random = new Random();
    private boolean isRolling = false;

    public RollCallApp() {
        setTitle("学生点名系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1600, 1000);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout(10, 10));

        // 设置背景颜色
        getContentPane().setBackground(new Color(240, 245, 249));

        initUI();

        setVisible(true);
    }

    private void initUI() {
        // 顶部面板 - 文件选择
        JPanel topPanel = createTopPanel();
        add(topPanel, BorderLayout.NORTH);

        // 中间面板 - 显示区域
        JPanel centerPanel = createCenterPanel();
        add(centerPanel, BorderLayout.CENTER);

        // 底部面板 - 控制按钮
        JPanel bottomPanel = createBottomPanel();
        add(bottomPanel, BorderLayout.SOUTH);

        // 右侧面板 - 已点名单
        JPanel rightPanel = createRightPanel();
        add(rightPanel, BorderLayout.EAST);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        panel.setBorder(BorderFactory.createTitledBorder("文件选择"));
        panel.setBackground(Color.WHITE);

        loadButton = new JButton("选择学生名单");
        loadButton.addActionListener(e -> selectExcelFile());
        styleButton(loadButton, new Color(70, 130, 180), 20);

        fileLabel = new JLabel("未选择文件");
        fileLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        fileLabel.setForeground(new Color(100, 100, 100));

        panel.add(loadButton);
        panel.add(fileLabel);

        return panel;
    }

    private JPanel createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("点名显示"));
        panel.setBackground(Color.WHITE);

        displayLabel = new JLabel("准备点名", JLabel.CENTER);
        displayLabel.setFont(new Font("微软雅黑", Font.BOLD, 80));
        displayLabel.setForeground(new Color(70, 130, 180));
        displayLabel.setBorder(new EmptyBorder(50, 20, 50, 20));

        panel.add(displayLabel, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createBottomPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));
        panel.setBorder(BorderFactory.createTitledBorder("操作控制"));
        panel.setBackground(Color.WHITE);

        startButton = new JButton("开始点名");
        startButton.addActionListener(e -> startRollCall());
        styleButton(startButton, new Color(65, 105, 225), 30);

        stopButton = new JButton("停止点名");
        stopButton.addActionListener(e -> stopRollCall());
        styleButton(stopButton, new Color(220, 20, 60), 30);
        stopButton.setEnabled(false);

        JButton resetButton = new JButton("重置名单");
        resetButton.addActionListener(e -> resetList());
        styleButton(resetButton, new Color(205, 133, 63), 30);

        panel.add(startButton);
        panel.add(stopButton);
        panel.add(resetButton);

        return panel;
    }

    private JPanel createRightPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder("已点名学生"));
        panel.setPreferredSize(new Dimension(200, 0));
        panel.setBackground(Color.WHITE);

        listModel = new DefaultListModel<>();
        calledList = new JList<>(listModel);
        calledList.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        calledList.setBackground(new Color(250, 250, 250));

        JScrollPane scrollPane = new JScrollPane(calledList);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(200, 200, 200)));

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private void styleButton(JButton button, Color color, int fontSize) {
        button.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
        button.setBackground(color);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20));
    }

    private void selectExcelFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("Excel文件 (*.xlsx)", "xlsx"));
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            fileLabel.setText(selectedFile.getName());
            loadStudentsFromExcel(selectedFile);
        }
    }

    private void loadStudentsFromExcel(File file) {
        try (FileInputStream fis = new FileInputStream(file);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            studentList.clear();
            calledStudents.clear();
            listModel.clear();

            for (Row row : sheet) {
                Cell cellNo = row.getCell(1);
                Cell cellName = row.getCell(2);
                if (cellNo != null && cellName != null) {
                    String stuNo = cellNo.getStringCellValue().trim();
                    String name = cellName.getStringCellValue().trim();
                    if (!name.isEmpty() && !stuNo.isEmpty() && stuNo.length() > 5) {
                        studentList.add(stuNo + " " + name);
                    }
                }
            }

            if (studentList.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Excel文件中未找到学生名单", "错误", JOptionPane.ERROR_MESSAGE);
                fileLabel.setText("未选择文件");
            } else {
                JOptionPane.showMessageDialog(this, "成功加载 " + studentList.size() + " 名学生", "成功", JOptionPane.INFORMATION_MESSAGE);
            }

        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "读取文件时出错: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            fileLabel.setText("未选择文件");
        }
    }

    private void startRollCall() {
        if (studentList.isEmpty()) {
            JOptionPane.showMessageDialog(this, "学生名单为空，请先加载名单", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        isRolling = true;
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
        loadButton.setEnabled(false);

        timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (isRolling) {
                    int index = random.nextInt(studentList.size());
                    displayLabel.setText(studentList.get(index));
                }
            }
        });

        timer.start();
    }

    private void stopRollCall() {
        isRolling = false;
        if (timer != null) {
            timer.stop();
        }

        startButton.setEnabled(true);
        stopButton.setEnabled(false);
        loadButton.setEnabled(true);

        String selectedStudent = displayLabel.getText();
        if (!calledStudents.contains(selectedStudent)) {
            calledStudents.add(selectedStudent);
            listModel.addElement(selectedStudent);
        }
    }

    private void resetList() {
        int result = JOptionPane.showConfirmDialog(this,
                "确定要重置名单吗？这将清空已点名学生",
                "确认重置",
                JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            calledStudents.clear();
            listModel.clear();
            displayLabel.setText("准备点名");
        }
    }

    public static void main(String[] args) {
        // 设置UI风格
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 启动应用
        SwingUtilities.invokeLater(() -> new RollCallApp());
    }
}
